package com.shimao.celnet.payment.controller;


import com.shimao.celnet.payment.form.ASysRoleForm;
import com.shimao.celnet.payment.form.SelectTree;
import com.shimao.celnet.payment.model.ASysRole;
import com.shimao.celnet.payment.service.ASysRoleService;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色控制类
 * Created by ensure on 2017/4/26./roles/list
 */
@Controller
@RequestMapping("/roles")
public class ASysRoleController {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private ASysRoleService aSysRoleService;

    /**
     * 分页列表
     * @param formBean 页面对象
     * @param pageActionNm 分页提交按钮名称
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public  String getByPage(@ModelAttribute ASysRoleForm formBean, String pageActionNm, Model model){
        logger.info("列表页面初始化--开始");
        if(StringUtils.isNotEmpty(formBean.getGuid())){
            //更新，新增后，重新刷新情况，查询条件清空
            formBean=new ASysRoleForm();
        }
        //当前页码设定
        int pageNum=FinalUtil.PAGE_Fist_NUM;
        if(formBean.isIsLastPage()){
            pageNum=formBean.getPages();
        }
        if(StringUtils.isNotEmpty(pageActionNm) && !"0".equals(pageActionNm)){
            pageNum=Integer.valueOf(pageActionNm);
        }
        //页面数据查询结果
        model.addAttribute("formBean", aSysRoleService.getByPage(formBean, pageNum, FinalUtil.PAGE_LENGHT));

        return "role/roleList";
    }


    /**
     * 新增初始化
     * @param
     * @return
     */
    @RequestMapping("/addInfo")
    public  String  addInfo(@ModelAttribute  ASysRoleForm formBean, Model model) {
        formBean.setTreeList(aSysRoleService.creatPermissionTree(""));
        model.addAttribute("formBean",formBean);
        return "role/roleInfo";
    }


    /**
     * 更新初始化
     * @param
     * @return
     */
    @RequestMapping("/editInfo")
    public String   editInfo(@RequestParam String guid, Model model) {
        ASysRoleForm aSysRoleForm = new ASysRoleForm();
        //编辑数据取得
        ASysRole aSysRole = aSysRoleService.getByKey(guid);
        aSysRoleForm.setRoleName(aSysRole.getRoleName());
        aSysRoleForm.setRemark(aSysRole.getRemark());
        aSysRoleForm.setGuid(aSysRole.getGuid());

        aSysRoleForm.setTreeList(aSysRoleService.creatPermissionTree(guid));
        model.addAttribute("formBean",aSysRoleForm);
        return "role/roleInfo";
    }


    /**
     * 新增保存
     * @param
     * @return
     */
    @RequestMapping("/addSave")
    public  @ResponseBody Map<String, Object> addSave(@RequestBody @Valid ASysRoleForm formBean, BindingResult result) {
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();

        //界面输入验证
        if (result.hasErrors()) {
            for(FieldError error:result.getFieldErrors()) {
                returnMap.put(error.getField() + FinalUtil.VALID_MSG, error.getDefaultMessage());
                //验证错误==2
                returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_2);
            }
            return returnMap;
        }


        try{
            //数据新增，角色对应权限guid取得
            Map<String, String> guidMap = new HashMap<String, String>();
            List<SelectTree> treesList =formBean.getTreeList();
            for(SelectTree selectTree:treesList){
                guidMap.put(selectTree.getGuid(),selectTree.getGuid());
            }
            // 当前用户GUID取得
            ASysRole aSysRole =new ASysRole();
            aSysRole.setRoleName(formBean.getRoleName());
            aSysRole.setRemark(formBean.getRemark());

            aSysRoleService.save(aSysRole, guidMap);

            //新增成功消息==0
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_SCU_4);
//            returnMap.put(FinalUtil.SAVE_SCU_URL, "/roles/list");
            logger.debug(FinalUtil.PAGE_ADD_SCU);

        } catch (Exception e) {
            //新增失败消息==1
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_1);
            returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_ADD_ERR);
            e.printStackTrace();
            logger.error(FinalUtil.PAGE_ADD_ERR);
            logger.error(e);
        }

        return returnMap;
    }

    /**
     * 更新保存
     * @param
     * @return
     */
    @RequestMapping("/editSave")
    public  @ResponseBody Map<String, Object> editSave(@RequestBody @Valid ASysRoleForm formBean,BindingResult result) {
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();

        //界面输入验证
        if (result.hasErrors()) {
            for(FieldError error:result.getFieldErrors()) {
                returnMap.put(error.getField() + FinalUtil.VALID_MSG, error.getDefaultMessage());
                //验证错误==2
                returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_2);
            }
            return returnMap;
        }
        //数据新增，角色对应权限guid取得
        Map<String, String> guidMap = new HashMap<String, String>();
        List<SelectTree> selectTreeLs =formBean.getTreeList();
        for(SelectTree selectTree:selectTreeLs){
            guidMap.put(selectTree.getGuid(),selectTree.getGuid());

        }

        try{
            //数据修改，角色对应权限guid取得
            // 当前用户GUID取得
            ASysRole aSysRole =new ASysRole();
            aSysRole.setGuid(formBean.getGuid());
            aSysRole.setRoleName(formBean.getRoleName());
            aSysRole.setRemark(formBean.getRemark());

            aSysRoleService.update(aSysRole,guidMap);

            //更新成功消息==4，左侧菜单刷新
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_SCU_4);
//            returnMap.put(FinalUtil.SAVE_SCU_URL, "/roles/list");
            logger.debug(FinalUtil.PAGE_UPD_SCU);
        } catch (Exception e) {
            //新增失败消息
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_1);
            returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_UPD_ERR);
            e.printStackTrace();
            logger.error(FinalUtil.PAGE_UPD_ERR);
            logger.error(e);
        }

        return returnMap;
    }

    /**
     * 删除
     * @param
     * @return
     */
    @RequestMapping("/delete")
    public @ResponseBody Map<String, Object> delete(@RequestBody String guid){
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            //删除角色
            aSysRoleService.delete(guid);

            //成功消息==0
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_SCU_0);
            logger.debug(FinalUtil.PAGE_DEL_SCU);
        } catch (Exception e) {
            //失败消息
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_1);
            returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_DEL_ERR);
            e.printStackTrace();
            logger.error(FinalUtil.PAGE_DEL_ERR);
            logger.error(e);
        }

        return returnMap;
    }


}
